<?php

use think\facade\Db;

function success($data = [], $msg = '操作成功')
{
    return json([
        'code' => 1,
        'msg' => $msg,
        'data' => $data
    ]);
}

function error($msg = '操作失败', $code = 400, $data = [])
{
    return json([
        'code' => 0,
        'msg' => $msg,
        'data' => $data
    ]);
}

function createRandStr($length = 8)
{
    $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $randStr = '';
    for ($i = 0; $i < $length; $i++) {
        $randStr .= $str[mt_rand(0, strlen($str) - 1)];
    }
    return $randStr;
}

function signToken($userId, $mobile)
{
    $data = [
        // 签发人
        'iss' => request()->domain(),
        // 签发时间
        'iat' => time(),
        // 自定义数据
        'data' => [
            'user_id' => $userId,
            'mobile' => $mobile,
        ]
    ];
    $key = config('app.jwt_key');
    $token = \Firebase\JWT\JWT::encode($data, $key, 'HS256');
    return $token;
}

function checkSmsCode($mobile, $code)
{
    $log = Db::name('sms_code_log')->where('mobile', $mobile)->find();
    if (!$log) {
        return false;
    }
    if ($log['code'] != $code) {
        return false;
    }
    if (time() - $log['send_time'] > 300) {
        Db::name('sms_code_log')->where('mobile', $mobile)->delete();
        return false;
    }
    Db::name('sms_code_log')->where('mobile', $mobile)->delete();
    return true;
}



function add_money_log($user_id, $money, $reason, $type = 1)
{
    // 获取用户信息
    $user = Db::name('usertable')->where('id', $user_id)->find();
    if (!$user) {
        throw new Exception('用户不存在');
    }

    if ($type == 1){
        $newBalance = $user['wallet'] + $money;
    } elseif ($type == 0){
        $newBalance = $user['wallet'] - $money;
    } else {
        throw new Exception('无效的类型');
    }

    // 更新用户余额
    Db::name('usertable')->where('id', $user_id)->update(['wallet' => $newBalance]);

    // 记录流水
    Db::name('money')->insert([
        'user_id' => $user_id,
        'money' => $money,
        'reason' => $reason,
        'before' => $user['wallet'],
        'after' => $newBalance,
        'type' => $type,
        'create_time' => date('Y-m-d H:i:s')
    ]);

    return $newBalance;
}

function get_transaction_logs($user_id)
{
    // 查询用户的流水记录
    $logs = Db::name('money')
        ->where('user_id', $user_id)
        ->order('create_time', 'desc')
        ->select();

    if (!$logs) {
        throw new Exception('没有找到流水记录');
    }

    return $logs;
}
